package com.weijun.keepalive_daemon.service

import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.os.Parcelable
import com.weijun.keepalive_daemon.DaemonKeepAlive
import com.weijun.keepalive_daemon.activity.OnePixelActivity
import com.weijun.keepalive_daemon.logE
import com.weijun.keepalive_daemon.receiver.ScreenStatusManager
import com.weijun.keepalive_daemon.utils.IntentUtils
import com.weijun.keepalive_daemon.utils.MediaPlayerUtil
import com.weijun.keepalive_daemon.utils.ROMUtils
import java.util.concurrent.TimeUnit

/**
 * @author: weijun
 * date: 2023/7/6
 * description:
 */
internal class CoreService : BaseService(), Handler.Callback,ScreenStatusManager.Observer {

    private val mHandler by lazy(LazyThreadSafetyMode.NONE) { Handler(Looper.getMainLooper(),this) }

    override fun onCreate() {
        super.onCreate()
        "CoreService onCreate".logE()
        ScreenStatusManager.addObserver(this)
        if (!ROMUtils.isXiaomi() && DaemonKeepAlive.musicPlayEnabled) {
            MediaPlayerUtil.init(this)
        }
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        super.onStartCommand(intent, flags, startId)
        "CoreService onStartCommand".logE()
        val intent2 = intent?.getParcelableExtra<Parcelable>(KEY_INTENT) as Intent?
        if (intent == null || START_ACTIVITY != intent.action || intent2 == null) {
            return START_STICKY
        }
        val isOppo = ROMUtils.isOppo()
        if (isOppo) {
            MediaPlayerUtil.init(this)
        }
        IntentUtils.startActivitySafe(applicationContext, intent2)
        if (!isOppo) {
            return START_STICKY
        }
        mHandler.postDelayed({ stopSelf() }, 5000)
        return START_STICKY
    }

    override fun onDestroy() {
        super.onDestroy()
        ScreenStatusManager.removeObserver(this)
        MediaPlayerUtil.stop()
    }

    override fun handleMessage(msg: Message): Boolean {
        when (msg.what) {
            STOP_MUSIC_MESSAGE -> MediaPlayerUtil.stop()
            STAT_MUSIC_MESSAGE -> MediaPlayerUtil.init(this)
        }
        return true
    }

    override fun screenStatusChanged(screenOn: Boolean) {
        if (screenOn) {
            OnePixelActivity.finishIfExist()
            mHandler.sendEmptyMessageDelayed(STOP_MUSIC_MESSAGE, STOP_MUSIC_DELAY)
            return
        }
        if (!ROMUtils.isHuawei() && DaemonKeepAlive.onePxEnabled) {
            IntentUtils.startActivitySafe(DaemonKeepAlive.application, OnePixelActivity::class.java)
        }
        if (!ROMUtils.isXiaomi() && DaemonKeepAlive.musicPlayEnabled) {
            mHandler.sendEmptyMessage(STAT_MUSIC_MESSAGE)
        }
    }

    companion object {
        private const val STOP_MUSIC_MESSAGE = 1
        private const val STAT_MUSIC_MESSAGE = 2
        private val STOP_MUSIC_DELAY = TimeUnit.MINUTES.toMillis(1)
        private const val START_ACTIVITY = "start_activity"
        private const val KEY_INTENT = "intent"

        fun startForLockScreen(context:Context,intent:Intent){
            IntentUtils.startActivitySafe(context, intent)
            val intent2 = Intent(context, CoreService::class.java).apply {
                putExtra(KEY_INTENT, intent)
                action = START_ACTIVITY
            }
            try {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    context.startForegroundService(intent2)
                } else {
                    context.startService(intent2)
                }
            } catch (ignore: Exception) { }
        }
    }
}